package com.xtc.netty.io.bio;

import com.xtc.netty.io.bio.http.MyRequest;
import com.xtc.netty.io.bio.http.MyResponse;
import com.xtc.netty.io.bio.http.MyServlet;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Administrator
 */
public class MyTomcat {

    private int port = 9090;
    private ServerSocket server;
    private Map<String, MyServlet> servletMapping = new HashMap<>();
    private Properties webXml = new Properties();

    private void init() {
        try {
            InputStream inputStream = MyTomcat.class.getClassLoader().getResourceAsStream("web.properties");
            webXml.load(inputStream);

            for (Map.Entry<Object, Object> map : webXml.entrySet()) {
                String key = (String) map.getKey();
                if (key.endsWith(".url")) {
                    String servletName = key.replaceAll("\\.url$", "");
                    String url = (String) map.getValue();
                    String className = webXml.getProperty(servletName + ".className");
                    MyServlet myServlet = (MyServlet) Class.forName(className).newInstance();

                    // 单实例，多线程
                    servletMapping.put(url, myServlet);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start() {
        // 1、加载配置文件,初始化servletMapping
        this.init();

        try {
            server = new ServerSocket(this.port);

            // 2、用一个死循环来等待用户请求
            while (true) {
                Socket socket = server.accept();

                // 3、HTTP请求,发送的数据就是字符串，有规律的字符串(HTTP协议)
                process(socket);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void process(Socket socket) throws Exception {
        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();

        MyRequest myRequest = new MyRequest(inputStream);
        MyResponse myResponse = new MyResponse(outputStream);

        String url = myRequest.getUrl();
        if (servletMapping.containsKey(url)) {
            servletMapping.get(url).service(myRequest, myResponse);
        } else {
            myResponse.write("404 not found!");
        }

        outputStream.flush();
        outputStream.close();

        inputStream.close();
        socket.close();
    }

    public static void main(String[] args) {
        new MyTomcat().start();
    }
}
